package com.senior.threadlocal;

public class ThreadLocalDemo {


    public static void main(String[] args) {
        House house = new House();
        new Thread(()->{
            try {
                for (int i = 0; i <3 ; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName() + "卖出" + house.threadLocal.get() + "套");
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //增加remove，是为了避免内存泄露
                house.threadLocal.remove();
            }
        },"1").start();

        new Thread(()->{
            for (int i = 0; i <4 ; i++) {
                house.saleHouse();
            }
            System.out.println(Thread.currentThread().getName() + "卖出" + house.threadLocal.get() + "套");
        },"2").start();

        new Thread(()->{
            for (int i = 0; i <5 ; i++) {
                house.saleHouse();
            }
            System.out.println(Thread.currentThread().getName() + "卖出" + house.threadLocal.get() + "套");
        },"3").start();

        System.out.println(Thread.currentThread().getName() + "卖出" + house.threadLocal.get() + "套");
    }

}
class House{

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(()->0);

    //这个和上面写的是一个意思
//    ThreadLocal<Integer> threadLocal2 = new ThreadLocal<Integer>(){
//        @Override
//        protected Integer initialValue() {
//            return 0;
//        }
//    };

    public void saleHouse(){
        Integer value = threadLocal.get();
        ++value;
        threadLocal.set(value);
    }
}
